package com.atguigu.flink.chapter07.timer;

import com.atguigu.flink.bean.WaterSensor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.util.Collector;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/9/18 10:24
 */
public class Flink01_Timer_1 {
    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 20000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(2);
    
        SingleOutputStreamOperator<String> main = env
            .socketTextStream("hadoop162", 9999)
            .map(line -> {
                String[] data = line.split(",");
                return new WaterSensor(data[0], Long.valueOf(data[1]), Integer.valueOf(data[2]));
            })
            .keyBy(WaterSensor::getId)
            .process(new ProcessFunction<WaterSensor, String>() {
                @Override
                public void processElement(WaterSensor value,
                                           Context ctx,
                                           Collector<String> out) throws Exception {
                    // 如果水位的值超过了20则,5s之后发出预警信息, 预警信息写入到侧输出流
                    if (value.getVc() > 20) {
                        // 注册定时器, 5s之后触发
                        long now = System.currentTimeMillis();
                        System.out.println("now = " + now);
                        ctx.timerService().registerProcessingTimeTimer(now + 5000);
                    }
                    
                    
                    
                }
    
                // 定时器触发的时候, 会自动执行这个方法
                @Override
                public void onTimer(long timestamp,  // 定时器触发的时间
                                    OnTimerContext ctx, //
                                    Collector<String> out) throws Exception {
                    out.collect("有水位超过了20, 红色预警..." + timestamp);
                }
            });
    
        main.print();
    
        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
